from .models import Welcome,Banner, Notice,Collection,Area
from django.http import JsonResponse
from rest_framework.mixins import ListModelMixin,DestroyModelMixin,CreateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from .serializer import BannerSerializer, NoticeSerializer,CollectionSerializer,AreaSerializer,CollectionSaveSerializer
from datetime import datetime
# from libs.baidu_ai import BaiDuAI
from libs.baidu_ai import BaiDuFace
from django.db.models import Count
from django.db.models.functions import Trunc
from .serializer import StatisticsListSerializer
from django.conf import settings

# 广告页接口
def welcome(request):
    res = Welcome.objects.all().order_by('order').first() #找出最大的图片排序
    img = settings.BACKEND_url+'/media/' + str(res.img)
    print(res.img)
    return JsonResponse({'code':100,'msg':'is ok','result':img})


#轮播图接口
class BannerView(GenericViewSet, ListModelMixin):
    queryset = Banner.objects.all().filter(is_delete=False).order_by('order')[:3]
    serializer_class = BannerSerializer

    def list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        notice = Notice.objects.all().order_by('create_time').first()
        serializer = NoticeSerializer(instance=notice)
        return Response({'code': 100, 'msg': '成功', 'banner': res.data, 'notice': serializer.data})


# 采集列表
class CollectionView(GenericViewSet,ListModelMixin,DestroyModelMixin,CreateModelMixin):
    # 查出当天的--》没过滤当前用户
    queryset = Collection.objects.all().filter(create_time__gte=datetime.now().date())
    print(queryset)
    serializer_class = CollectionSerializer

    def get_serializer_class(self):
        if self.action == 'create':
            return CollectionSaveSerializer
        else:
            return CollectionSerializer

    def list(self, request, *args, **kwargs):
        res=super().list(request, *args, **kwargs)
        today_count=len(self.get_queryset())
        return Response({'code':100,'msg':'成功','result':res.data,'today_count':today_count})

    #删除人脸
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        # 百度ai中删除
        baidu = BaiDuFace()
        res = baidu.delete(instance.name_pinyin,instance.face_token)
        # print(res)
        self.perform_destroy(instance)
        return Response()



# 网格列表
class AreaView(GenericViewSet,ListModelMixin):
    queryset = Area.objects.all()
    serializer_class = AreaSerializer




class StatisticsView(GenericViewSet, ListModelMixin):
    # 做个分组
    queryset = Collection.objects.annotate(date=Trunc('create_time', 'day')).values('date').annotate(
        count=Count('id')).values('date', 'count')
    serializer_class = StatisticsListSerializer


class FaceView(GenericViewSet):
    def create(self, request, *args, **kwargs):
        # 1 取出前端传入的人脸照片
        avatar_object = request.data.get('avatar')
        if not avatar_object:
            return Response({'code': 103, 'msg': '请正常提交人脸'})
        # 2 使用百度人脸库--》搜索
        ai = BaiDuFace()
        res = ai.search(avatar_object)
        if res.get('error_code')==0:
            # 3 查到了，取出userid--》能匹配成功多个，咱们只取第一条
            user_id=res.get('result').get('user_list')[0].get('user_id')
            score=int(res.get('result').get('user_list')[0].get('score'))
            # 4 去咱们采集库，查出用户详情
            user=Collection.objects.filter(name_pinyin=user_id).first()
            return Response({'code':100,'msg':'匹配成功','name':user.name,'score':score})
        else:
            return Response({'code': 102, 'msg': '该人员不是咱们社区人员，请注意'})